package com.chenwang.measure.ui.activity;


import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenwang.measure.MyApp;
import com.chenwang.measure.R;
import com.chenwang.measure.base.BaseActivity;
import com.chenwang.measure.model.Constant;
import com.chenwang.measure.model.bean.LocationBean;
import com.chenwang.measure.model.bean.MainBean;
import com.chenwang.measure.receiver.BtStateReceiver;
import com.chenwang.measure.ui.adapter.MainActivityAdapter;
import com.chenwang.measure.ui.dialog.ConnectDeviceDialog;
import com.chenwang.measure.utils.BlueConnectTask;
import com.chenwang.measure.utils.BluetoothUtil;
import com.chenwang.measure.utils.ByteDataUtils;
import com.chenwang.measure.utils.DistanceUtils;
import com.chenwang.measure.utils.FileUtils;
import com.chenwang.measure.utils.MyCrashHandler;
import com.chenwang.measure.utils.MyLogger;
import com.chenwang.measure.utils.MyToast;
import com.chenwang.measure.utils.RxTime;
import com.chenwang.measure.utils.SharePreferenceUtils;
import com.chenwang.measure.utils.TimeUtils;
import com.tencent.bugly.crashreport.BuglyLog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

//主页
@RuntimePermissions
public class MainActivity extends BaseActivity implements BtStateReceiver.Listener, BaseQuickAdapter.OnItemClickListener, BlueConnectTask.BlueConnectListener {

    private static long lastBackTime = 0;//上一次点击 back 键的时间,用于双击退出的判断
    private final int BACK_INTERVAL = 1000;//当双击 back 键在此间隔内是直接触发 onBackPressed
    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.tv_lat)
    TextView mTvLat;       //纬度
    @BindView(R.id.tv_lon)
    TextView mTvLon;      //经度
    @BindView(R.id.tv_height)
    TextView mTvHeight;  //高
    @BindView(R.id.tv_status)
    TextView mTvStatus;  //连接状态设备
    @BindView(R.id.tv_satellite_total)
    TextView mTvSatelliteTotal;  //   卫星数
    @BindView(R.id.tv_satellite)//改为精度
    TextView mTvSatellite;//
    @BindView(R.id.tv)
    TextView mTextView;  //显示测试信息 改为显示cors值
    @BindView(R.id.tv_location_status)
    TextView mTvLocationStatus;//定位状态 0未解算 16单点定位 17差分定位 50固定解 34浮点
    private List<MainBean> mList;     //主页图标文字
    private ConnectDeviceDialog mDialog; //连接提示对话框
    private BtStateReceiver mReceiver;   //监听设备连接状态
    private int mMode; //当前模式 1 2 3

    @Override
    public int setLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        MainActivityPermissionsDispatcher.callWithCheck(this); //获取权限
        initRecyclerView();//初始化主界面
        mReceiver = new BtStateReceiver(this,this );//注册蓝牙广播状态
        Constant.logFile= TimeUtils.getTodayDateTime() +".txt";//按时间生成log文件

    }

    //模拟经纬度方便测试
    private double mD;
    private void a(){
        mD = 0.0;
        final Random ra =new Random();
        RxTime rxTime = new RxTime();
        rxTime.interval(1000, new RxTime.RxAction() {
            @Override
            public void action(long number) {
                double d=ra.nextDouble();
                double dd = ra.nextDouble();
                d = d/100000;
                dd = dd/100000;
                mD = d;
                LocationBean.getInstance().setLat(DistanceUtils.decimalSeven(45.1234567123+mD));
                LocationBean.getInstance().setHight(3.1234567123+mD);
                LocationBean.getInstance().setLon(DistanceUtils.decimalSeven(126.1234567123+dd));
                LocationBean.getInstance().setPos(50);
                LocationBean.getInstance().setHightOffset(0.44454f);
                LocationBean.getInstance().setLonOffset(0.44454f);
                LocationBean.getInstance().setLatOffset(0.42342f);
                LocationBean.getInstance().setStaellite("10");
                LocationBean.getInstance().setLatOffset(0.12f);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        open();//打开蓝牙
        connect();//连接设备
        LocationBean.getInstance().setOkMsg(false);//主页每次设为false
        mMode = SharePreferenceUtils.getInt(this, "device_mode", 0);//获取当前模式 123
    }

    //权限
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION})
    void call() {
    }

    //连接设备
    private void connect() {
         //判断是否连接过
        if (!BluetoothUtil.isBluetoothconnect(this)) {
            MyToast.show("未连接过设备, 打开蓝牙连接设备");
            mTvStatus.setText("设备未连接");
        } else {
            if (MyApp.getBluetoothSocket() == null) {
                showDialogConnect();//显示连接对话框
                BluetoothDevice device = BluetoothUtil.queryBluetooth(BluetoothUtil.getMac(this));
                //连接设备
                BlueConnectTask connectTask = new BlueConnectTask(device.getAddress());
                connectTask.setBlueConnectListener(this);
                connectTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, device);
            } else {
               MyLogger.i("   ");
            }
        }
    }






    /**
     * 发送指令
     * @param socket
     */
    private void send(BluetoothSocket socket){
        try {
            MyLogger.i("发送指令");
            socket.getOutputStream().write("unlogall\r\n".getBytes());//清空Log
            socket.getOutputStream().write("log com3 bestposb ontime 1\r\n\"".getBytes());//42
            socket.getOutputStream().write("log com3 m925b ontime 3\r\n".getBytes()); //925
            socket.getOutputStream().write("log com3 psrdopb ontime 5\r\n".getBytes());//174
            socket.getOutputStream().write("log com3 refstationb ontime 5\r\n".getBytes());//175
            socket.getOutputStream().write("log com3 satmsga ontime 1\r\n".getBytes());//911
       /*   socket.getOutputStream().write("set datalink gprs on\r\n".getBytes());//打开gprs
            socket.getOutputStream().write("tst gprsmsg on\r\n".getBytes());//打开GPRS日志
            socket.getOutputStream().write("tst connect com2 gprs\r\n".getBytes());
            socket.getOutputStream().write("interfacemode gprs auto auto on\r\n".getBytes());
            socket.getOutputStream().write("set datalink gprs cors param hljcors.hl 192.189.3.27 2101 TCP Client\r\n".getBytes());
            socket.getOutputStream().write("set datalink gprs cors srctable RTCM32 ydkjgs1 kjgs4491\r\n".getBytes());
            socket.getOutputStream().write("set datalink gprs status\r\n".getBytes());*/
            socket.getOutputStream().write("saveconfig\r\n".getBytes());
        } catch (IOException e) {
            //捕获异常保存到文件
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);
            MyToast.show("连接失败 退出重试");
            MyLogger.i(e.getMessage());
            mTvStatus.setText("设备未连接");
        }

    }



    /**
     * 设备连接回调
     * @param address 蓝牙mac
     * @param socket
     */
    @Override
    public void onBlueConnect(String address, final BluetoothSocket socket) {
        if (socket != null ) {
            MyToast.show("连接设备成功");
            MyApp.setBluetoothSocket(socket);
            mTvStatus.setText("设备已连接");
            read();//读取数据
            send(socket);//发送初始指令

        } else {
            mTvStatus.setText("设备未连接");
            MyToast.show("连接设备失败");
        }
        dismissDialog();
    }



    //报文解析
    private void read(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] b= new byte[1024];//每次从设备中读取的数据
                    byte[] buffer ;//最新字节
                    byte[] lastBuffer = new byte[0];//剩余字节
                    int len =0;//读取长度
                    //循环读取字节流
                    while ((MyApp.getBluetoothSocket()!=null)&&(len = MyApp.getBluetoothSocket().getInputStream().read(b)) != -1) {
                        try {

                            buffer = ByteDataUtils.subBytes(b, 0, len);//将读取到的数据赋值给buffer
                            MyLogger.i(buffer.length + "字节长度" + len);
                            if (LocationBean.getInstance().isSource()) {//判断是否获取源数据
                                LocationBean.getInstance().setMessgae(new String(buffer, 0, len));
                            }
                            MyLogger.i("上次剩余" + lastBuffer.length);
                            //拼接上次剩余与本次读取字节
                            buffer = ByteDataUtils.byteMerger(lastBuffer, ByteDataUtils.subBytes(buffer, 0, len));
                            lastBuffer = new byte[0];
                            len = buffer.length;//字节长度
                            MyLogger.i(len+"");

                            //解析指令返回结果OK!
                            if (LocationBean.getInstance().isOkMsg()) {

                                for (int i = 0; i < buffer.length - 2; i++) {
                                    //循环查找OK!
                                    String o = new String(ByteDataUtils.subBytes(buffer, i, 1));
                                    String k = new String(ByteDataUtils.subBytes(buffer, i + 1, 1));
                                    String s = new String(ByteDataUtils.subBytes(buffer, i + 2, 1));
                                    if (o.equals("O") && k.equals("K") && s.equals("!")) {
                                       //将OK!保存
                                        String ok = new String(buffer, i, 3);
                                        LocationBean.getInstance().setOk("OK!");
                                        MyLogger.i("  " +ok);
                                        FileUtils.log("指令返回结果："+ok);
                                        lastBuffer = new byte[0];
                                        break;
                                    } else {
                                        //保存剩余字节
                                        lastBuffer = ByteDataUtils.subBytes(buffer, i, len - i);
                                    }
                                }

                            }else {
                                if (len < 1200) {//保证字节长度在1200到28之间
                                    if (len > 28) {
                                        for (int i = 0; i < len - 10; i++) {
                                            //解析开头
                                            String aa = Integer.toHexString(buffer[i] & 0xff);
                                            String s44 = Integer.toHexString(buffer[i + 1] & 0xff);
                                            String s12 = Integer.toHexString(buffer[i + 2] & 0xff);
                                            if (aa.equals("aa") && s44.equals("44") && s12.equals("12")) {//找报文开头aa 44 12
                                                //解析42
                                                if (ByteDataUtils.getShort(ByteDataUtils.subBytes(buffer, i + 4, 2)) == 42) {
                                                    if (len > (105 + i)) {//防止数组越界
                                                        String aaa = Integer.toHexString(buffer[i + 104] & 0xff);//下段报文开头aa
                                                        String s4 = Integer.toHexString(buffer[i + 105] & 0xff);//下段报文开头44
                                                        if ((aaa.equals("aa")) && (s4.equals("44"))) {//保证报文完整
                                                            show42(ByteDataUtils.subBytes(buffer, i, 104));
                                                            lastBuffer = ByteDataUtils.subBytes(buffer, 104 + i, len - (104 + i));
                                                            i = 104 + i;//将i设置读取的位置
                                                            MyLogger.i(i + "!!!!!!!!!" + 42 + "--------" + lastBuffer.length);

                                                        } else {//保存剩余 退出 读取下一次
                                                            lastBuffer = ByteDataUtils.subBytes(buffer, i, len - i);
                                                            MyLogger.i("len:" + len + "     i" + i);
                                                            MyLogger.i(i + "!!!!!!!!!" + 42 + "-----" + lastBuffer.length);
                                                            break;
                                                        }

                                                    } else {//保存剩余 退出 读取下一次
                                                        lastBuffer = ByteDataUtils.subBytes(buffer, i, len - i);
                                                      //  MyLogger.i(42 + "！！！！！！！！" + lastBuffer.length);
                                                        break;
                                                    }
                                                }
                                                //解析925
                                                if ((i < len - 11)) {
                                                    if (ByteDataUtils.getShort(ByteDataUtils.subBytes(buffer, i + 4, 2)) == 925) {
                                                        int l = ByteDataUtils.getShort(ByteDataUtils.subBytes(buffer, i + 8, 2));//报文长度
                                                        if (l > 0) {//数组越界
                                                            if (len > (l + i + 7 + 28)) {
                                                                String aaa = Integer.toHexString(buffer[i + l + 4 + 28] & 0xff);//aa
                                                                String s4 = Integer.toHexString(buffer[i + l + 5 + 28] & 0xff);//44
                                                                if ((aaa.equals("aa")) && (s4.equals("44"))) {
                                                                    show925(ByteDataUtils.subBytes(buffer, i, l + 28 + 4));
                                                                    lastBuffer = ByteDataUtils.subBytes(buffer, l + 28 + 4 + i, len - (l + 28 + 4 + i));
                                                                    i = l + i + 4 + 28-1;
                                                                    MyLogger.i(Integer.toHexString(buffer[i] & 0xff)+"!!!!!!!!!!"+i + Integer.toHexString(lastBuffer[0] & 0xff) + "925!!!" + lastBuffer.length);
                                                                } else {
                                                                    lastBuffer = ByteDataUtils.subBytes(buffer, i, len - i);
                                                                    MyLogger.i("925跳aaa444" + lastBuffer.length);
                                                                    break;
                                                                }

                                                            } else {
                                                                lastBuffer = ByteDataUtils.subBytes(buffer, i, len - i);
                                                                MyLogger.i("925跳！！！！" + lastBuffer.length);
                                                                break;
                                                            }
                                                        }
                                                    } else {
                                                      //  MyLogger.i(i+"925--------------");
                                                    }

                                                }else {
                                                   /* lastBuffer = ByteDataUtils.subBytes(buffer, i, len - i);
                                                   // MyLogger.i("925跳长度" + lastBuffer.length);
                                                    break;*/
                                                }
                                               //  lastBuffer = ByteDataUtils.subBytes(buffer, i, len - i);
                                               // MyLogger.i(i+"最后" + lastBuffer.length);

                                            }
                                        }
                                        if (lastBuffer.length>5){
                                        //MyLogger.i("最后！！！"+lastBuffer.length+"!!!!!"+Integer.toHexString(lastBuffer[0] & 0xff)+"!!!!!"
                                         //       +ByteDataUtils.getShort(ByteDataUtils.subBytes(lastBuffer, 4, 2)));
                                                   }


                                    } else {
                                        lastBuffer = ByteDataUtils.byteMerger(lastBuffer, ByteDataUtils.subBytes(buffer, 0, len));
                                        // MyLogger.i("小于28剩余长度"+lastBuffer.length);
                                    }
                                }
                            }

                        }catch (Exception e){
                                //异常保存文件
                                lastBuffer = new byte[0];
                                MyCrashHandler.newInstance().saveCrashInfoToFile(e);
                                MyLogger.i(e.getMessage());
                           }

                    }


                    LocationBean.getInstance().setState(false);//设备未连接
                    LocationBean.getInstance().clear();//清空经纬度信息
                } catch (IOException e) {
                    MyCrashHandler.newInstance().saveCrashInfoToFile(e);
                    MyLogger.i(e.getMessage());
                }

            }
        }).start();
        dismissLoading();
    }


    /**
     * 925
     * @param buffer 925报文字节
     */
    private void show925(final byte[] buffer){
        int cors = buffer[ 28 + 60] & 0xff; //cors 值
        LocationBean.getInstance().setCosr(cors);
        MyLogger.i(cors+"网络状态");
        if (mMode==2) {//等于2cors模式才执行
            if (cors == 7 || cors == 15) {
                if (cors != LocationBean.getInstance().getLastCors()) {
                    if (cors == 7)
                        MyToast.show("Cors连接断开");
                    if (cors == 15)
                        MyToast.show("Cors连接上了");

                }
            }
        }
        LocationBean.getInstance().setLastCors(cors);
        mTextView.post(new Runnable() {
            @Override
            public void run() {
                mTextView.setText("cors状态:"+(buffer[ 28 + 60] & 0xff)+"");
            }
        });
       //  MyLogger.i((buffer[ 28 + 2] & 0xff)+"cprs信号强度");
      //  MyLogger.i((buffer[ 28 + 10] & 0xff)+"工作模式");
      //  FileUtils.log("cors状态："+(buffer[ 28 + 60] & 0xff));

    }

    private int i=0; //测试
    /**
     *
     * @param buffer 42报文字节
     */
    private void show42(byte[] buffer){
        MyLogger.i("42");
        int h = 28;
        //  h = (Integer.valueOf(ByteDataUtils.binary(ByteDataUtils.subBytes(buffer, 3, 1), 2), 2));
        MyLogger.d(ByteDataUtils.getInt(ByteDataUtils.subBytes(buffer, h, 4)) + "解状态");
        MyLogger.d(ByteDataUtils.getInt(ByteDataUtils.subBytes(buffer, h + 4, 4)) + "定位状态");
        MyLogger.d(ByteDataUtils.getDouble(ByteDataUtils.subBytes(buffer, h + 8, 8)) + "纬度" + ByteDataUtils.subBytes(buffer, h + 8, 8).length);
        MyLogger.d(ByteDataUtils.getDouble(ByteDataUtils.subBytes(buffer, h + 16, 8)) + "经度");
        MyLogger.d(ByteDataUtils.getDouble(ByteDataUtils.subBytes(buffer, h + 24, 8)) + "高度");
        MyLogger.d(ByteDataUtils.getFloat(ByteDataUtils.subBytes(buffer, h + 40, 4)) + "纬度差");
        MyLogger.d(ByteDataUtils.getFloat(ByteDataUtils.subBytes(buffer, h + 44, 4)) + "经度差");
        MyLogger.d(ByteDataUtils.getFloat(ByteDataUtils.subBytes(buffer, h + 48, 4)) + "高度差");
        //高
        if (!(ByteDataUtils.getDouble(ByteDataUtils.subBytes(buffer, h + 24, 8)) + "").contains("-")) {
            LocationBean.getInstance().setHight(DistanceUtils.decimalSeven(ByteDataUtils.getDouble(ByteDataUtils.subBytes(buffer, h + 24, 8))));
        } else {
            LocationBean.getInstance().setHight(0.0);
        }
        //纬度
        if (!(ByteDataUtils.getDouble(ByteDataUtils.subBytes(buffer, h + 8, 8)) + "").contains("-")) {
            LocationBean.getInstance().setLat(DistanceUtils.decimalSeven(ByteDataUtils.getDouble(ByteDataUtils.subBytes(buffer, h + 8, 8))));
        } else {
            LocationBean.getInstance().setLat(0.0);
        }
        //经度
        if (!(ByteDataUtils.getDouble(ByteDataUtils.subBytes(buffer, h + 16, 8)) + "").contains("-")) {
            LocationBean.getInstance().setLon(DistanceUtils.decimalSeven(ByteDataUtils.getDouble(ByteDataUtils.subBytes(buffer, h + 16, 8))));
        } else {
            LocationBean.getInstance().setLon(0.0);
        }
        //高差
        if (!(ByteDataUtils.getFloat(ByteDataUtils.subBytes(buffer, h + 48, 4))+"").contains("-")){
            LocationBean.getInstance().setHightOffset(ByteDataUtils.getFloat(ByteDataUtils.subBytes(buffer, h + 48, 4)));

        }//纬度差
        if (!(ByteDataUtils.getFloat(ByteDataUtils.subBytes(buffer, h + 40, 4))+"").contains("-")){
            LocationBean.getInstance().setLatOffset(ByteDataUtils.getFloat(ByteDataUtils.subBytes(buffer, h + 40, 4)));

        }//经度差
        if (!(ByteDataUtils.getFloat(ByteDataUtils.subBytes(buffer, h + 44, 4))+"").contains("-")){
            LocationBean.getInstance().setLonOffset(ByteDataUtils.getFloat(ByteDataUtils.subBytes(buffer, h + 44, 4)));

        }
        LocationBean.getInstance().setSatelliteTotal((buffer[h + 64] & 0xff) + "");//卫星
        LocationBean.getInstance().setStaellite((buffer[h + 65] & 0xff) + "");//卫星
        LocationBean.getInstance().setSol(ByteDataUtils.getInt(ByteDataUtils.subBytes(buffer, h, 4)));//
        LocationBean.getInstance().setPos(ByteDataUtils.getInt(ByteDataUtils.subBytes(buffer, h + 4, 4)));//解状态
        LocationBean.getInstance().setState(true);
        if (LocationBean.getInstance().getPos() == 0) {
            LocationBean.getInstance().clear();
        }
        mTvLocationStatus.post(new Runnable() {
            @Override
            public void run() {
                setLocationStatus(LocationBean.getInstance().getPos());
            }
        });

        mTvLat.post(new Runnable() {
            @Override
            public void run() {
                mTvLat.setText("纬度：" + LocationBean.getInstance().getLat());
            }
        });
        mTvLon.post(new Runnable() {
            @Override
            public void run() {
                mTvLon.setText("经度：" + LocationBean.getInstance().getLon());
            }
        });


        mTvHeight.post(new Runnable() {
            @Override
            public void run() {
                mTvHeight.setText("高度：" + LocationBean.getInstance().getHight());
            }
        });
        mTvSatelliteTotal.post(new Runnable() {
            @Override
            public void run() {
                mTvSatelliteTotal.setText(/*(i++)+*//*LocationBean.getInstance().getHightOffset()+"!!!!!!"+LocationBean.getInstance().getLatOffset()+"!!!!"+LocationBean.getInstance().getLonOffset()+*/"卫星总数：" + LocationBean.getInstance().getSatelliteTotal());
            }
        });
        mTvSatellite.post(new Runnable() {
            @Override
            public void run() {
                mTvSatellite.setText("水平:" + DistanceUtils.decimalFour(LocationBean.getInstance().getHorizontal()) + " 高:" + DistanceUtils.decimalFour(LocationBean.getInstance().getVertrcal()));
            }
        });
      //  FileUtils.log("定位状态："+LocationBean.getInstance().getPos());//解状态保存log
      //  FileUtils.log("经纬度："+LocationBean.getInstance().getLon()+","+LocationBean.getInstance().getLat());//解状态保存log


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);//取消监听
        try {   //关闭Socket 并设置为空
            if (MyApp.getBluetoothSocket() != null)
                MyApp.getBluetoothSocket().close();
                MyApp.setBluetoothSocket(null);
        } catch (IOException e) {
           MyLogger.e(e.getMessage());
        }

    }



    @OnClick(R.id.tv_clear)
    public void onViewClicked() {
      showDialogClear();
    }


    /**
     * 设备连接断开回调
     * @param state true设备连接 false 设备断开
     */
    @Override
    public void onState(boolean state) {
        try {
            if (state) {
                mTvStatus.setText("设备已连接");
                LocationBean.getInstance().setState(true);
            } else {
                MyToast.show("设备已断开");
                mTvStatus.setText("设备未连接");
                if (MyApp.getBluetoothSocket() != null)
                    MyApp.getBluetoothSocket().close();
                MyApp.setBluetoothSocket(null);
                LocationBean.getInstance().setState(false);
                LocationBean.getInstance().clear();
                clearShowState();
            }
        }catch (IOException e) {
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);
        }
    }

    //将经纬度信息清空
    private void clearShowState(){
        if (mTvLat != null) {
            mTvLat.setText("纬度：0");
        }
        if (mTvLon !=null) {
            mTvLon.setText("经度：0" );
        }
        if (mTvHeight!= null) {
            mTvHeight.setText("高度：0" );
        }
        if (mTvLocationStatus != null){
            setLocationStatus(0);
        }
        if (mTvSatelliteTotal != null) {
            mTvSatelliteTotal.setText("卫星总数：0" );
            if (mTvSatellite != null) {
                mTvSatellite.setText("水平:0  高:0" );
            }
        }
        LocationBean.getInstance().clear();
    }

    //清空
    private void showDialogClear(){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("清空所有数据");
        normalDialog.setMessage("是否删除退出");
        normalDialog.setCancelable(false);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        FileUtils.deleteFile(Constant.path+Constant.fileName);
                        SharePreferenceUtils.clear(MainActivity.this);
                        finish();

                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        normalDialog.show();

    }
    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastBackTime < BACK_INTERVAL) {
            super.onBackPressed();
        } else {
            Toast.makeText(this, "双击 back 退出", Toast.LENGTH_SHORT).show();
        }
        lastBackTime = currentTime;
    }

    /**
     * 设置定位状态
     * @param status  解状态 0 16 17 50 34
     */
    private void setLocationStatus(int status) {
        switch (status) {
            case 0:
                mTvLocationStatus.setText("未解算: 0");
                break;
            case 16:
                mTvLocationStatus.setText("单点定位: 16");
                break;
            case 17:
                mTvLocationStatus.setText("差分定位: 17");
                break;
            case 50:
                mTvLocationStatus.setText("固定解: 50");
                break;
            case 18:
                mTvLocationStatus.setText("SBAS: 18");
                break;
            case 34:
                mTvLocationStatus.setText("浮点解: 34");
                break;
        }

    }

    //显示连接设备
    private void showDialogConnect() {
        try {
            mDialog = new ConnectDeviceDialog();
            mDialog.show(getSupportFragmentManager(), "");
        }catch (Exception e){
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);
        }
    }

    //关闭对话框
    private void dismissDialog() {
        try {
            if (mDialog != null && mDialog.getDialog() != null && mDialog.isAdded()) {
                mDialog.dismiss();
            }
        } catch (Exception e) {
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);
    }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        switch (mList.get(position).getIcon()) {
            case R.mipmap.ic_bluetooth:

                //蓝牙
                startActivity(new Intent(this, BluetoothActivity.class));
                break;
            //任务
            case R.mipmap.ic_task_manage:
                startActivity(new Intent(this, TaskManageActivity.class));
                break;
            //测量
            case R.mipmap.ic_measure:
                int state = SharePreferenceUtils.getInt(this, "measure_finish", 0);
                if (state == 1) {
                    startActivity(new Intent(this, MeasureActivity.class));
                } else {
                    MyToast.show("没有测量的任务");
                }
                break;
            //模式设定
            case R.mipmap.ic_device_mode:
                startActivity(new Intent(this, DeviceModeActivity.class));
                break;
            case R.mipmap.ic_setting:
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.mipmap.ic_freedom:
                startActivity(new Intent(this, FreedomActivity.class));
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return super.onKeyUp(keyCode, event);
        }
        if (keyCode == 131){
            return true;
        }

        long currentTime = System.currentTimeMillis();
        if (currentTime - lastBackTime < BACK_INTERVAL) {

        } else {
            switch (keyCode) {
                case 8:
                    //蓝牙
                    startActivity(new Intent(this, BluetoothActivity.class));
                    break;
                //任务
                case 9:
                    startActivity(new Intent(this, TaskManageActivity.class));
                    break;
                //测量
                case 10:
                    int state = SharePreferenceUtils.getInt(this, "measure_finish", 0);
                    if (state == 1) {
                        startActivity(new Intent(this, MeasureActivity.class));
                    } else {
                        MyToast.show("没有测量的任务");
                    }
                    break;
                //模式设定
                case 11:
                    startActivity(new Intent(this, DeviceModeActivity.class));
                    break;
                case 12:
                    startActivity(new Intent(this, FreedomActivity.class));
                    break;

                default:
                    return super.onKeyUp(keyCode, event);


            }
        }
        lastBackTime = currentTime;
        return true;
    }

    //初始化 界面
    private void initRecyclerView() {
        mList = new ArrayList<>();
        mList.add(new MainBean(R.mipmap.ic_bluetooth, "蓝牙"));
        mList.add(new MainBean(R.mipmap.ic_device_mode, "模式"));
        mList.add(new MainBean(R.mipmap.ic_task_manage, "任务"));
        mList.add(new MainBean(R.mipmap.ic_measure, "测量"));
        mList.add(new MainBean(R.mipmap.ic_freedom, "自由"));
        mRv.setLayoutManager(new GridLayoutManager(this, 2));
        MainActivityAdapter adapter = new MainActivityAdapter(mList);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(MainActivity.this,CommandActivity.class));
                return true;
            }
        });
        mRv.setAdapter(adapter);
    }


}
